package com.foolishbird.sdk.ui.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.handler.SimpleAsyncResponseHandler;
import com.foolishbird.sdk.params.BindPhoneResponseParams;
import com.foolishbird.sdk.params.FloatKefuResponseParams;
import com.foolishbird.sdk.params.FloatNoticeResponseParams;
import com.foolishbird.sdk.params.ResponseParams;
import com.foolishbird.sdk.params.SendVerifyResponseParams;
import com.foolishbird.sdk.params.bean.FloatUserInfo;
import com.foolishbird.sdk.params.bean.State;
import com.foolishbird.sdk.params.bean.VerifyType;
import com.foolishbird.sdk.ui.activity.UserLoginActivity;
import com.foolishbird.sdk.ui.assist.OnFinishActivityListener;
import com.foolishbird.sdk.ui.assist.OnPhoneVerifyCodeListener;
import com.foolishbird.sdk.ui.assist.VerifyCodeCountDownTimer;
import com.foolishbird.sdk.ui.view.DialogFactory;
import com.foolishbird.sdk.utils.MyFragmentManger;
import com.foolishbird.sdk.utils.ResUtils;
import com.foolishbird.sdk.utils.ToolsUtils;


public class FloatPhoneUnbindFragment extends BaseHttpFragment implements View.OnClickListener , OnPhoneVerifyCodeListener {


//    private LinearLayout phoneLayout,realnameLayout,versionLayout,pwdLayout;
    private TextView titleTxt;
    private ImageView backView;
    EditText phoneText,codeText;
    Button confirmBtn,codBtn;

    private VerifyCodeCountDownTimer mCountDownTimer;

    @Override
    public void onStop() {
        super.onStop();
        onCancelCountDownTimer();
    }
    String oldCode;

    @Override
    public void onStartCountDownTimer() {
        Button sendVerifyCodeBtn = getSendVerifyCodeView();
        if (sendVerifyCodeBtn.isClickable()) {
            sendVerifyCodeBtn.setClickable(false);
        }

        if (mCountDownTimer == null) {
            mCountDownTimer = new VerifyCodeCountDownTimer(sendVerifyCodeBtn);
        }
        mCountDownTimer.start();
    }

    @Override
    public void onCancelCountDownTimer() {
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }

        Button sendVerifyCodeBtn = getSendVerifyCodeView();
        if (!sendVerifyCodeBtn.isClickable()) {
            sendVerifyCodeBtn.setClickable(true);
            sendVerifyCodeBtn.setText(ResUtils.getStringIdentifier(getActivity(), "hnssn_get_captcha"));
        }
    }

    protected Button getSendVerifyCodeView() {
        return codBtn;
    }

    @Override
    public void onCallbackVerifyCode(String verifyCode) {

    }

    public static final FloatPhoneUnbindFragment newInstance(Bundle bundle) {
        FloatPhoneUnbindFragment fragment = new FloatPhoneUnbindFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        int resource = ResUtils.getLayoutIdentifier(getActivity(), "fb_fragment_float_unbind_phone");
        View contentView =inflater.inflate(resource,null);
        titleTxt = contentView.findViewById(getViewIdentifier("fb_fragment_float_title"));
        titleTxt.setText("绑定手机");
        backView = contentView.findViewById(getViewIdentifier("fb_fragment_login_back"));
        backView.setOnClickListener(this);
        phoneText = contentView.findViewById(getViewIdentifier("fb_fragment_phone"));
        phoneText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
                if(keyCode ==  EditorInfo.IME_ACTION_NEXT&&getSendVerifyCodeView().isClickable()){
                    sendPhoneVerifyCode();
                }
                Log.e("OnKeyListener",keyCode+".."+(event==null));
                return false;
            }
        });
        codeText = contentView.findViewById(getViewIdentifier("fb_fragment_login_code_edit"));
        confirmBtn = contentView.findViewById(getViewIdentifier("fb_fragment_login_login_btn"));
        codBtn = contentView.findViewById(getViewIdentifier("fb_fragment_login_code_send"));
        confirmBtn.setOnClickListener(this);
        codBtn.setOnClickListener(this);
        oldCode = getArguments()!=null&&getArguments().containsKey("code")?getArguments().getString("code"):"";
        return contentView;

    }

    private FloatUserInfo userInfo;



    @Override
    public void onClick(View view) {
        if(view == backView){
//            if(userInfo!=null&&!TextUtils.isEmpty(userInfo.getId_number())){
//
//            }
            MyFragmentManger.getInstance().goBack(this);
        }else if(view == confirmBtn){
            String phoneNumber = phoneText.getText().toString().trim();
            String code = codeText.getText().toString().trim();
            if(TextUtils.isEmpty(phoneNumber)){
                Toast.makeText(getContext(),"请输入手机号",Toast.LENGTH_SHORT).show();
            }else if (TextUtils.isEmpty(code)){
                Toast.makeText(getContext(),"请输入验证码",Toast.LENGTH_SHORT).show();
            }else{
                SimpleAsyncResponseHandler handler = requestCallbackHandler(BindPhoneResponseParams.class);
                if(TextUtils.isEmpty(oldCode)){
                    HttpEngineApi.getInstance().bindPhoneNumber(phoneNumber, code, "", "", handler);
                }else {
                    HttpEngineApi.getInstance().changePhone(oldCode,code,phoneNumber,handler);
                }
            }


        } else if (view ==codBtn) {
            sendPhoneVerifyCode();

        }

//        OnFinishActivityListener listener = getOnFinishActivityListener();
//        if (listener != null) {
//            listener.doFinishActivity(this);
//        }
    }

    private void sendPhoneVerifyCode(){
        String phoneNumber = phoneText.getText().toString().trim();

        if (TextUtils.isEmpty(phoneNumber)) {
            String message = getString(ResUtils.getStringIdentifier(getActivity(), "hnssn_hint_telephonenumber"));
            DialogFactory.createConfirmDialog(getActivity(), message).show();
            return;
        }

        if (!ToolsUtils.checkCellphone(phoneNumber)) {
            String message = getString(ResUtils.getStringIdentifier(getActivity(), "hnssn_hint_phonecurrent"));
            DialogFactory.createConfirmDialog(getActivity(), message).show();
            return;
        }

        SimpleAsyncResponseHandler handler = requestCallbackHandler(FloatKefuResponseParams.class);
        taskid = HttpEngineApi.getInstance().getFloatCode(phoneNumber, VerifyType.PHONE_VERIFY.getValue(), handler);
    }

    private int taskid ;

    @Override
    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
        super.onAsyncRequestResult(flag, response, params);
        if (response != null) {
            int code = response.getState().getCode();
            if (State.SUCCESS == code) {
                if (taskid == flag) {
                    onStartCountDownTimer();
                    Toast.makeText(getContext(),"获取验证码成功",Toast.LENGTH_SHORT).show();
                }else if (response instanceof BindPhoneResponseParams){
                    Toast.makeText(getContext(),"绑定成功",Toast.LENGTH_SHORT).show();
                    HttpEngineApi.getInstance().getEngineConduits().writeNeedBindPhone(false);
                    MyFragmentManger.getInstance().goBack(this);
                }
            }
        }
    }

    private OnFinishActivityListener getOnFinishActivityListener() {
        if (!isNullContext()) {
            Activity activity = getActivity();
            if (activity instanceof OnFinishActivityListener) {
                return (OnFinishActivityListener) activity;
            }
        }
        return null;
    }
}
